<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2023-05-15 09:40:11
 * @LastEditors: wiz
 * @LastEditTime: 2023-05-19 15:57:50
-->
<template>
  <div
    :class="[
      'container',
      { enabled: G_enabled },
      { codeEditorBackground: readonly }
    ]"
  >
    <code-editor
      ref="codeInput"
      :config="G_codeEditorConf"
      @on-editor-changes="onEditorChanges"
    ></code-editor>
  </div>
</template>
<script lang="ts">
import { T_srv, codeEditor, codeEditorConf, vue } from './config';

@T_srv.comp({ components: { codeEditor } })
export default class T_codeInput extends vue {
  @T_srv.ref(`codeInput`) refCodeInput: any;

  @T_srv.prop({ required: true, type: String, default: '' })
  value: string;

  @T_srv.prop({ type: Boolean, default: true })
  readonly: boolean;

  @T_srv.watch(`readonly`, { immediate: true, deep: false })
  onReadonly(val: boolean, oldVal: boolean) {
    this.refCodeInput && this.setReadonly(val);
  }

  @T_srv.watch(`value`, { immediate: true, deep: true })
  onSetValue(val: string, oldVal: string) {
    this.refCodeInput &&
      // 只接收来自外部的数据传入更新
      !this.refCodeInput.G_editor.doc.cm.hasFocus() &&
      this.setValue(val);
  }

  private G_enabled: boolean = false;

  private G_codeEditorConf: any = {};

  created() {
    this.G_codeEditorConf = codeEditorConf();
  }

  mounted() {
    this.refCodeInput.G_editor.setValue(this.value);
    this.setReadonly(this.readonly);
  }

  private setValue(v: string) {
    this.refCodeInput.G_editor.setValue(v);
  }

  private setReadonly(val: boolean) {
    this.G_enabled = !val;
    this.refCodeInput.G_editor.doc.cm.setOption(`readOnly`, val);
    // 光标闪时间 -1 代表不需要光标
    this.refCodeInput.G_editor.doc.cm.setOption(
      `cursorBlinkRate`,
      val ? -1 : 530
    );
  }

  onEditorChanges(e) {
    this.$emit(`input`, e.doc.getValue());
    this.$emit(`on-changes`, e);
  }
}
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 6px;
  border-radius: 6px;
  border: 1px solid #f2f3f5;
}

.enabled:hover {
  border-radius: 6px;
  border: 1px solid #5cadff;
}

.codeEditorBackground {
  ::v-deep .CodeMirror {
    background: #f3f3f3;
  }
}
</style>
